package com.ganzalang.gmall.learning.netty.nio.zerocopy;

import lombok.extern.slf4j.Slf4j;

import java.io.FileInputStream;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @description: NIO的客户端
 * @author: Ganzalang
 * @Date 2021/7/15 15:32
 */
@Slf4j
public class NewIOClient {

    public static void main(String[] args) throws Exception{
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress("localhost", 7002));
        String fileName = "D:\\file01.txt";

        // 得到一个文件Channel
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();
        long start = System.currentTimeMillis();

        // Linux下一个transferTo方法就可以完成传输
        // 在windows 下一次调用transferTo只能发送8m，就需要分段传输，要记录传输的位置
        // transferTo底层使用零拷贝技术
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);
        log.info("发送总的字节数为{}，总耗时为{}", transferCount, (System.currentTimeMillis() - start));

        fileChannel.close();
    }
}
